import json

import re

import requests

import time

from django.shortcuts import redirect, render, HttpResponse


class Spider:
    def __init__(self):
        self.__Domain = "https://66cg11.com"
        
        self.__Headers = {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
        }
    
    # 获取板块列表Plates
    def PlatesList(self):
        SpiderUrl = "https://66cg11.com/front/api/v1/channels/list"
        response = requests.get(url=SpiderUrl, headers=self.__Headers).json()
        return response
    
    # 获取板块的内容
    def GetPlatesInfo(self, PlatesId, Page=1, PageSize=10):
        SpiderUrl = "https://66cg11.com/front/api/v1/posts/listByChannel"
        SpiderParams = {
            "pageNo": Page,
            "pageSize": PageSize,
            "channelId": PlatesId
        }
        if PlatesId is None:
            SpiderParams.pop("channelId")
        response = requests.get(url=SpiderUrl, params=SpiderParams, headers=self.__Headers).json()
        return response
    
    # 获取内容详情
    def GetChiGuaInfo(self, ChiGuaId):
        SpiderUrl = "https://66cg11.com/front/api/v1/posts/view/%s" % ChiGuaId
        html_text = requests.get(url=SpiderUrl, headers=self.__Headers).json()
        images = html_text["data"]["content"]
        # 正则表达式模式，匹配http或https开头的图片链接
        image_url_pattern = r'https?://\S+.(?:jpg|jpeg|png|gif|bmp)'
        # 使用re.findall找到所有匹配的图片链接
        image_urls = re.findall(image_url_pattern, images)
        # 提取内容
        news_text = re.findall('">(.*?)</', images, re.S)
        # 获取时间
        create_time = html_text['data']['created']
        
        # 获取标题
        title = html_text['data']['title']
        # 获取m3u8链接
        m3u8_url = html_text['data']['videoUrl']
        
        # 获取板块
        Plates = html_text['data']['channel']
        
        # 获取当前的id
        this_id = html_text['data']['id']
        # 获取此瓜的封面
        thumbnail = html_text['data']['thumbnail']
        Result = {
            "code": 200,
            "msg": "获取吃瓜成功",
            "data": {
                "news_text": news_text,
                "img_list": image_urls,
                "time": create_time,
                "title": title,
                "m3u8_url": m3u8_url,
                "Plates": Plates,
                "this_id": this_id,
                "thumbnail": thumbnail,
            }
        }
        return Result
    
    # 获取搜索内容
    def GetSearchInfo(self, search_text, Page=1, PageSize=10):
        SpiderUrl = "https://66cg11.com/front/api/v1/search"
        SpiderUrlParams = {
            "kw": search_text,
            "pageNo": Page,
            "pageSize": PageSize
        }
        response = requests.get(SpiderUrl, params=SpiderUrlParams, headers=self.__Headers).json()
        return response
    
    # 获取分类内容
    def GetTypeInfo(self, order="newest", pageNo=1, pageSize=10):
        SpiderUlr = "https://66cg11.com/front/api/v1/posts/listByChannel"
        SpiderParams = {
            "order": order,
            "pageNo": pageNo,
            "pageSize": pageSize
        }
        response = requests.get(url=SpiderUlr, params=SpiderParams, headers=self.__Headers).json()
        return response


spider = Spider()


# 获取分类内容
def GetTypeInfo(request):
    if request.method == 'GET':
        try:
            order = request.GET.get("order")
            pageNo = request.GET.get("Page")
            pageSize = request.GET.get("pageSize")
            Result = spider.GetTypeInfo(order, pageNo, pageSize)
        except Exception as e:
            Result = {"code": 500, "msg": "服务器错误", "data": {}}
        return HttpResponse(json.dumps(Result), status=200, content_type="application/json")


def GetPlatesList(request):
    if request.method == 'GET':
        try:
            Result = spider.PlatesList()
        except Exception as e:
            Result = {"code": 500, "msg": "服务器错误", "data": {}}
        return HttpResponse(json.dumps(Result), status=200, content_type="application/json")


# 获取板块的内容
def GetPlatesInfo(request):
    if request.method == 'GET':
        try:
            PlatesId = request.GET.get("PlatesId")
            Page = request.GET.get("Page")
            PageSize = request.GET.get("PageSize")
            Result = spider.GetPlatesInfo(PlatesId, Page, PageSize)
        except Exception as e:
            Result = {"code": 500, "msg": "服务器错误", "data": {}}
        return HttpResponse(json.dumps(Result), status=200, content_type="application/json")


# 获取内容详情
def GetChiGuaInfo(request):
    if request.method == 'GET':
        try:
            ChiGuaId = request.GET.get("ChiGuaId")
            if ChiGuaId is None:
                Result = {"code": 500, "msg": "ChiGuaId不能为空"}
                return HttpResponse(json.dumps(Result), status=Result["code"], content_type="application/json")
            Result = spider.GetChiGuaInfo(ChiGuaId=ChiGuaId)
            return HttpResponse(json.dumps(Result), status=Result["code"], content_type="application/json")
        except Exception as e:
            Result = {"code": 500, "msg": "服务器错误", "data": {}}
        return HttpResponse(json.dumps(Result), status=200, content_type="application/json")


# 获取搜索内容
def GetSearchInfo(request):
    if request.method == 'GET':
        try:
            SearchKey = request.GET.get("search_text")
            Page = request.GET.get("Page")
            PageSize = request.GET.get("PageSize")
            if SearchKey is None:
                Result = {"code": 500, "msg": "参数不正确"}
                return HttpResponse(json.dumps(Result), status=Result["code"], content_type="application/json")
            Result = spider.GetSearchInfo(search_text=SearchKey, Page=Page, PageSize=PageSize)
            return HttpResponse(json.dumps(Result), status=200, content_type="application/json")
        except Exception as e:
            Result = {"code": 500, "msg": "服务器错误", "data": {}}
